_express = require 'express'
_uuid = require 'node-uuid'
_Coal = require 'coal'
_async = require 'async'
_config = require('./config')


_coal = new _Coal(_config.db, _config.dev)
Model = _coal.Model('code')

app = _express()

###
  code
   -1 不存在
   1 存在但已经使用
  200 正常
  500 内部错误

###
app.get('/api/code/:code_id', (req, resp)->
  code_id = req.params.code_id
  return resp.jsonp(-1) if not code_id
  Code = Model.table()
  queue = []
  queue.push((cb)->
    Code.select('*').where({code: code_id})
    .then((rows)->
      console.log rows
      rows[0]
    )
    .then((code)->
      #记录不存在
      return cb(-1) if not code
      cb(null, code)
    )
    .catch((e)->
      console.log(e)
      cb(500)
    )
  )
  queue.push((code, cb)->
    return cb(1) if code.status isnt 1
    cb(null, code.id)
  )

  queue.push((id, cb)->
    Code.update({status: 0}).where({id: id})
      .then((result)->
        cb(null, 200)
      )
      .catch((e)->
        console.log e
        cb(500)
      )
  )

  _async.waterfall(queue, (error, result)->
    resp.jsonp(error or result)
  )
)

app.get('/api/code/list/all', (req, resp)->
  Code = Model.table()
  Code.select('*').then((data)->resp.send(data))
  .catch((e)->
    console.log e
  )
)


getRandomCode = (count)->
  return [] if not count
  return [] if typeof(count) isnt 'number'
  return [] if count < 1
  count = parseInt(count)
  result = []
  result.push({code: _uuid.v4(), status: 1}) for i in [1..count]
  result

generatorCode = (cb)->
  result = getRandomCode(20)
  Code = Model.table()
  Code.insert(result)
    .then((r)->
      console.log(r)
    )
    .catch((e)->
      console.log(e)
    )

app.use(_express.static('static'))
app.listen 8008